package com.revenant.driver.ui;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.apkfuns.logutils.LogUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.revenant.driver.R;
import com.revenant.driver.base.BaseActivity;
import com.revenant.driver.bean.BaseBean.MessageEvent;
import com.revenant.driver.bean.Selectareabean;
import com.revenant.driver.bean.WebUrlBean;
import com.revenant.driver.bean.XieYIStatusBean;
import com.revenant.driver.ui.activity.DriverOrderActivity;
import com.revenant.driver.ui.activity.OrderActivity;
import com.revenant.driver.utils.Constants;
import com.revenant.driver.utils.EventBusUtil;
import com.revenant.driver.utils.GsonUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wendu.dsbridge.DWebView;

import static com.revenant.driver.bean.BaseBean.MyEventCode.Order_Type_SIGAL;
import static com.revenant.driver.utils.Constants.Driver_Agreen_Con;
import static com.revenant.driver.utils.Constants.Look_Xieyi;

public class XieYiActivity extends BaseActivity {
    @BindView(R.id.webtest)
    DWebView webtest;

    String weburl = "";
    @BindView(R.id.close_img)
    ImageView closeImg;
    @BindView(R.id.xieyilclick)
    Button xieyilclick;
    View alertselect;
    boolean isselect = false;
    @BindView(R.id.show_alert)
    FrameLayout showAlert;
    FrameLayout.LayoutParams lp;

    private int showcount = 0;
    private String orderId = "";

    private PopupWindow popalert;
    private int jumpstatus = -1;


    @Override
    public int getContentViewResId() {
        return R.layout.activity_web_xieyi;

    }

    @Override
    public void initView() {
        alertselect = View.inflate(this, R.layout.alert_agreen_select, null);
        CheckBox checkBox = (CheckBox) alertselect.findViewById(R.id.select_box);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isselect = isChecked;
            }
        });

        weburl = getIntent().getStringExtra("weburl");
        orderId = getIntent().getStringExtra("conorderId");
        getstatus(orderId, 0);
        if (weburl != null) {
            if (weburl.length() > 0) {
                showDig();
                webtest.loadUrl(weburl);
            }
        }


        webtest.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webtest.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {


                dismissDig();


            }

        });

        lp = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        lp.gravity = Gravity.BOTTOM;
        lp.leftMargin = 20;
        lp.bottomMargin = 80;


        webtest.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                int v1 = Math.round(webtest.getContentHeight() * webtest.getScale());

                int v2 = (webtest.getHeight() + webtest.getScrollY());
                int i = showAlert.getChildCount();
                if (v1 - v2 >= 220) {

                    if (showAlert.getChildCount() == 3) {
                        showAlert.removeView(alertselect);
                    }
                } else {
                    if (showAlert.getChildCount() == 2) {
                        showAlert.addView(alertselect, lp);

                    }
                }


            }
        });
        initAlert();

    }

    @Override
    protected boolean isshowtitlebar() {
        return false;
    }

    @Override
    public void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.close_img, R.id.xieyilclick})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.close_img:
                darkenBackground(0.3f);
                popalert.showAtLocation(webtest, Gravity.CENTER, 0, 0);

                break;
            case R.id.xieyilclick:
                if (!isselect) {
                    showToast("请勾选协议");
                } else {
                    showDig();
                    driveragree(orderId);
//                    JumpActivity(3);
                }
                break;
        }
    }

    private void initAlert() {
        View contentView = View.inflate(this, R.layout.alert_close_info, null);
        Button close = (Button) contentView.findViewById(R.id.go_back);
        Button ok = (Button) contentView.findViewById(R.id.go_confirm);
        popalert = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true
        );

        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                popalert.dismiss();

                jumpOrder();
            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popalert.dismiss();
            }
        });
        popalert.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        // 设置PopupWindow是否能响应外部点击事件
        popalert.setOutsideTouchable(false);
        // 设置PopupWindow是否能响应点击事件
        popalert.setTouchable(true);

        popalert.setAnimationStyle(R.style.Popupwindow);

        popalert.setContentView(contentView);

        popalert.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                darkenBackground(1f);
            }
        });


    }

    private void darkenBackground(Float alpha) {
        if (alpha < 0 || alpha > 1) {
            return;
        }
        WindowManager.LayoutParams windowLP = getWindow().getAttributes();
        windowLP.alpha = alpha;
        if (alpha == 1) {
            //不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        } else {
            //此行代码主要是解决在华为手机上半透明效果无效的bug
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        }
        getWindow().setAttributes(windowLP);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (popalert != null) {
            popalert.dismiss();
        }
    }

    private void JumpActivity(int position) {
        Bundle bundle = new Bundle();
        bundle.putInt("orderselect", position);
        Intent intent1 = new Intent(this, DriverOrderActivity.class);
        intent1.putExtras(bundle);
        startActivity(intent1);
        finish();
    }

    private void driveragree(String orderId) {
        OkGo.<String>post(Driver_Agreen_Con)
                .params("orderId", orderId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        WebUrlBean webUrlBean = GsonUtil.parseJsonWithGson(response.body(), WebUrlBean.class);
                        if (webUrlBean.getCode().contains("0")) {
                            MessageEvent event = new MessageEvent(Order_Type_SIGAL);
                            EventBusUtil.sendEvent(event);
                            popalert.dismiss();
                            jumpOrder();

                        } else {
                            showToast(webUrlBean.getMsg());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();
                    }
                });

    }


    private void getstatus(String id, int type) {

        OkGo.<String>get(Constants.Search_Status_XieYi)
                .params("id", id)
                .params("type", type)

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        XieYIStatusBean xieYIStatusBean = GsonUtil.parseJsonWithGson(response.body(), XieYIStatusBean.class);
                        if (xieYIStatusBean.getCode().contains("0")) {
                            jumpstatus = xieYIStatusBean.getData();
                        }
                    }
                });

    }

    private void jumpOrder() {
        switch (jumpstatus) {
            case 2:
                JumpActivity(3);
                break;
            case 8:
                JumpActivity(4);
                break;
        }
    }


}
